<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Sms;
use app\common\model\Role;
use app\common\model\RoomPeople;
use fast\Random;
use app\common\model\Room as modelRoom;
use think\Db;
use think\exception\PDOException;
use think\exception\ValidateException;
use think\Request;
use app\common\model\User as modelUser;

class Compere extends Api
{
    protected $noNeedLogin = ["compereLogin"];
    protected $noNeedRight = ["*"];

    public function __construct(Request $request = null)
    {
        parent::__construct($request);
    }

    /** 主持人密码登录 */
    public function compereLogin()
    {
        $param = $this->request->param();
        $this->validateCommon("Compere.compereLogin", $this->serial_number);
        $compereInfo = \app\common\model\User::where(['mobile' => $param['mobile'], 'position' => 2])->find();
        if (!$compereInfo) $this->error('手机号错误');
        if ($param['passWord'] != $compereInfo['password']) $this->error('密码错误');
        $this->auth->direct($compereInfo['id']);
        $this->success('', $this->auth->getUserinfo());
    }

    /**指定角色&&随机角色 */
    public function setRole()
    {
        $param = $this->request->param();
        $this->validateCommon("Compere.setRole", $this->serial_number);
        $roomId   = numberDecode($param['roomNumber']);
        $userId   = numberDecode($param['userNumber']);
        $roomInfo = modelRoom::get($roomId);
        if(!$roomInfo) $this->error('房间不存在');
        if(empty($roomInfo->role_ids)) $this->error('未设置房间角色,请联系管理员后台设置');
        $roleIdArr = explode(',',$roomInfo->role_ids);
        if ($param['type'] == 1) {
            if (!$param['roomNumber']) $this->error('指定角色时,房间编号不能为空');
            if(!in_array($param['roleId'],$roleIdArr)) $this->error('角色未在房间设置,请联系管理员重新补充');
            $roleId = $param['roleId'];
        } else {
            $roleId    = array_rand($roleIdArr, 1);
        }
        $roleInfo = Role::get($roleId);
        if ($this->auth->id != $roomInfo->compere_id) {
            $this->error('当前操作用户非此房间主持人,暂无权限', '', 0, $this->serial_number);
        }
        if (!$roleInfo) $this->error('该角色不存在,请核对后再重新指定');
        $issetRoomUser = RoomPeople::where(['room_id' => $roomId, 'user_id' => $userId])->find();
        if (!$issetRoomUser) $this->error('该房间不存在该用户');
        if ($issetRoomUser['status'] == 2) $this->error('该用户角色已死亡');
        if (!empty($issetRoomUser['role_id'])) $this->error('该用户已设置角色,请勿重复设置');
        $data['role_id']   = $roleId;
        $data['role_name'] = $roleInfo->role_name;
        $res               = RoomPeople::where(['room_id' => $roomId, 'user_id' => $userId])->update($data);
        if ($res) $this->success('角色设置成功');
        $this->error('角色设置失败');
    }

    /** 杀死角色/复活角色 */
    public function controlRole()
    {
        $param = $this->request->param();
        $this->validateCommon("Compere.controlRole", $this->serial_number);
        $roomId   = numberDecode($param['roomNumber']);
        $userId   = numberDecode($param['userNumber']);
        $roomInfo = modelRoom::get($roomId);
        if ($this->auth->id != $roomInfo->compere_id) {
            $this->error('当前操作用户非此房间主持人,暂无权限', '', 0, $this->serial_number);
        }
        $rommPeopleInfo = RoomPeople::where(['room_id' => $roomId, 'user_id' => $userId, 'role_id' => $param['roleId']])->find();
        if (!$rommPeopleInfo) $this->error('该房间用户信息获取失败,请核对后重试');
        $res = false;
        if ($param['controlType'] == 1) {
            if ($rommPeopleInfo['status'] == 2) $this->error('该角色已经死亡不能执行杀死操作');
            $res = RoomPeople::where(['room_id' => $roomId, 'user_id' => $userId, 'role_id' => $param['roleId']])->update(['status' => 2]);
        }
        if ($param['controlType'] == 2) {
            if ($rommPeopleInfo['status'] == 1) $this->error('该角色未死亡不能执行复活操作');
            $res = RoomPeople::where(['room_id' => $roomId, 'user_id' => $userId, 'role_id' => $param['roleId']])->update(['status' => 1]);
        }
        if ($res) $this->success('操作成功');
        $this->error('操作失败');
    }

    /** 开始游戏/结束游戏 */
    public function controlGame()
    {
        $param = $this->request->param();
        $this->validateCommon("Compere.controlGame", $this->serial_number);
        $roomId   = numberDecode($param['roomNumber']);
        $roomInfo = modelRoom::get($roomId);
        if (!$roomInfo) $this->error('房间不存在');
        if ($this->auth->id != $roomInfo->compere_id) {
            $this->error('当前操作用户非此房间主持人,暂无权限', '', 0, $this->serial_number);
        }
        $res = false;
        if ($param['controlGameType'] == 1) {
            if ($roomInfo->onlien_num < 2) $this->error('房间人数不足两人,无法开始游戏');
            $res = $roomInfo->save(['is_over' => 3]);
        }
        if ($param['controlGameType'] == 2) {
            $res = $roomInfo->save(['is_over' => 2]);
        }
        if ($res) $this->success('房间状态操作成功');
        $this->error('房间状态操作失败');
    }

    /** 选择胜利者 */
    public function searchWinUserArr()
    {
        $param = $this->request->param();
        $this->validateCommon("Compere.searchWinUserArr", $this->serial_number);
        $roomId   = numberDecode($param['roomNumber']);
        $roomInfo = modelRoom::get($roomId);
        if (!$roomInfo) $this->error('房间不存在');
        if ($roomInfo->is_over != 3) $this->error('当前房间状态无法结束');
        if ($this->auth->id != $roomInfo->compere_id) {
            $this->error('当前操作用户非此房间主持人,暂无权限', '', 0, $this->serial_number);
        }
        $userNumberArr = explode(',', $param['userNumberStr']);
        $newUserIdArr  = [];
        foreach ($userNumberArr as $k => $value) {
            $userId   = numberDecode($value);
            $roomUser = RoomPeople::where(['room_id' => $roomId, 'user_id' => $userId])->find();
            if (empty($roomUser)) {
                $newK = $k + 1;
                $this->error('第' . $newK . '位用户不在此房间内,请核对后重试');
            }
            $newUserIdArr[] = $userId;
        }
        $otherUserIdArr = RoomPeople::where(['room_id' => $roomId])->whereNotIn('user_id', $newUserIdArr)->column('user_id');
        $result         = false;
        Db::startTrans();
        try {
            RoomPeople::whereIn('user_id', $newUserIdArr)->where('room_id', $roomId)->update(['is_win' => 2]);
            RoomPeople::whereIn('user_id', $otherUserIdArr)->where('room_id', $roomId)->update(['is_win' => 3]);
            $roomInfo->save(['is_over' => 2]);
            $result =  modelUser::whereIn('id', $newUserIdArr)->setInc('score', 120);
            foreach ($newUserIdArr as $value){
               \app\common\model\User::score('120',$value,'胜利');
            }
            Db::commit();
        } catch (ValidateException|PDOException|Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        if (false === $result) {
            $this->error(__('结果判定成功'));
        }
        $this->success('结果判定失败,请重新判定');

    }

}